import { login as loginApi } from '@/api/login'
import router from '@/router'
import { setTokenTime } from '@/utils/auth'
export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '', // 存入token
    siderType: true, // 设置侧边栏是否隐藏,
    lang: localStorage.getItem('lang') || 'zh' // 当前使用语言，没有默认中文
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    changeSiderType(state) {
      state.siderType = !state.siderType
    },
    changLang(state, lang) {
      state.lang = lang
    }
  },
  actions: {
    // 登录操作,commit接收用户信息
    login({ commit }, userInfo) {
      // 发起请求loginApi,userInfo表示用户信息
      return new Promise((resolve, reject) => {
        loginApi(userInfo).then(res => {
          console.log(res, '登录成功了')
          commit('setToken', res.token) // 成功后调用vuex的set方法，把res的token传进去
          setTokenTime()
          router.replace('/') // 跳转首页
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录,把setToken设置为空,清空localStorage，跳转登录页面
    logout({ commit }) {
      commit('setToken', '')
      localStorage.clear()
      router.replace('/login')
    }
  }
}
